package handler

import (
	"adminSrv/dao"
	pb "adminSrv/proto"
	"adminSrv/utils"
	"context"
)

type AdminSrv struct{}

func (e *AdminSrv) ChangePassWord(ctx context.Context, req *pb.ChangePassWordRequest, resp *pb.Response) error {
	admin, cnt := dao.AdminLogin(req.Name, req.OldPassword)
	if cnt == 0 {
		resp.Code = "201"
		resp.Msg = "旧密码错误"
		return nil
	}
	admin.Password = utils.M5Encode(req.NewPassword)
	dao.GDB.Save(&admin)
	resp.Code = "200"
	resp.Msg = "修改密码成功"
	return nil
}

// Login
// ////////////////////////////////
//
//	@Description: 管理员登录
//	@receiver e
//	@param ctx
//	@param req
//	@param rsp
//	@return error
//
// ////////////////////////////////
func (e *AdminSrv) Login(ctx context.Context, req *pb.LoginRequest, rsp *pb.Response) error {
	admin, cnt := dao.AdminLogin(req.Name, req.Password)
	if cnt == 0 {
		rsp.Msg = "账号或者密码错误"
		rsp.Code = "201"
		rsp.Data = nil
		return nil
	}
	rsp.Msg = "登录成功"
	rsp.Code = "200"
	rsp.Data = &pb.Admin{
		Id:       int32(admin.Id),
		Username: admin.Username,
	}
	return nil
}

func (e *AdminSrv) Register(ctx context.Context, req *pb.LoginRequest, resp *pb.Response) error {
	_, cnt := dao.AdminLogin(req.Name, req.Password)
	if cnt == 0 {
		dao.AdminRegister(req.Name, req.Password)
		resp.Code = "200"
		resp.Msg = "注册成功"
		return nil
	}
	resp.Code = "201"
	resp.Msg = "注册失败，该账号已存在"

	return nil
}
